<script setup lang="ts">
import { getOptions } from '../../../utils/index.ts'
import type { FormItemTool } from '../../../types/index.ts'
import { find } from 'fair-wing'
// import type {
//   allDataType,
// } from '@/BaseComponent/SForm/src/types/index.ts'

type IProps = {
  item: FormItemTool<'treeSelect'>
  allDisabled: boolean
  isEditByRow: boolean
}

// const allChangeData = defineModel<allDataType['allChangeData']>('allChangeData', {
//   default: () => ({}),
// })
const emit = defineEmits(['specific'])
const props = withDefaults(defineProps<IProps>(), {isEditByRow: true,})
const { item, allDisabled, isEditByRow } = toRefs(props)
const value = defineModel<any>('value')
const elRef = useTemplateRef('elRef')
const getRef = () => {
  return elRef.value
}
defineExpose({
  getRef,
})

const options = computed(() => getOptions(item.value))
const currentOption = computed(() => {
  const data = find(options.value, {[item.value.config?.props?.value || 'value']: value.value})
  return data?.own ?? {}
})

watchEffect(() => {
  if(!item.value.field) return
  const optionAt = currentOption.value
  const label = optionAt ? optionAt[item.value.config?.props?.label || 'label'] : (value ?? '')
  emit('specific', { optionAt, value: value.value, label, options: options.value as any })
})

</script>
<template>
<span class="w-full">
  <el-tree-select
    v-if="isEditByRow"
    clearable
    ref="elRef"
    :disabled="allDisabled"
    :placeholder="'请选择' + item.label"
    :data="options"
    v-model="value"
    v-bind="item.config"
    v-on="item.eventFunction || {}"
  >
    <template v-for="slotName in item.slotNames" #[slotName]="slotData">
      <slot :name="slotName" :slotData="slotData"> </slot>
    </template>
  </el-tree-select>
  <span v-else> {{ currentOption.label ?? value }} </span>
</span>
</template>

<style scoped lang="scss"></style>
